<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\web\controller;

use app\common\helper\FormatHelper;
use app\common\model\Users;
use app\common\service\CommonService;
use app\common\service\EngineerService;
use app\web\constant\CommonConstant;
use think\Db;
use app\web\validate\User as UserValidate;
use think\Exception;
use think\Model;

/**
 * 技师控制器
 * @package app\index\controller
 */
class Engineer extends Auth
{
    public $noNeedLogin = [];

    /**
     * 获取全部技师
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();

            if (empty($getData['group'])) {
                $this->result('部门参数不能为空', '', 204);
            }
            $sql = Db::name('qt_users')
                ->field('id,post_id,real_name,age,phone,avatar,top_type_id,sex,work_status,content,work_time,status,work_number,card,discount');
            $where = [];
            //技师性别筛选
            if (!empty($getData['sex'])) {
                $where['sex'] = $getData['sex'];
            }
            //技师性别筛选
            if (!empty($getData['phone'])) {
                $where['phone'] = $getData['phone'];
            }
            //技师项目筛选
            if (!empty($getData['top_type_id'])) {
                $where['top_type_id'] = $getData['top_type_id'];
            }
            //技师工作状态筛选
            if (!empty($getData['work_status'])) {
                $where['work_status'] = $getData['work_status'];
            }
            //员工工作状态是否在职
            if (isset($getData['status'])) {
                if($getData['status'] == '0'){
                    $sql->whereIn('status',['0','1','2']);
                }else{
                    $where['status'] = $getData['status'];
                }
            }
            //职务
            if (!empty($getData['post_id'])) {
                $where['post_id'] = $getData['post_id'];
            }
            //技师工作状态筛选
            if (!empty($getData['order'])) {
                switch ($getData['order']) {
                    case '1';
                        $order = 'id asc';
                        break;
                    case '2';
                        $order = 'clock_down desc';
                        break;
                    default:
                        $order = 'id desc';
                }
                $where['work_status'] = $getData['work_status'];
            } else {
                $order = 'id desc';
            }
            //工号筛选
            if (!empty($getData['work_number'])) {
                $where['work_number'] = $getData['work_number'];
            }
            $limit = $getData['limit'];
            //其他筛选条件
            $where['store_id'] = $this->userInfo['store_id'];
            $where['group'] = $getData['group'];
            $engineer = $sql->where($where)->order($order)->paginate($limit)
                ->each(function ($item) {
                    $room_name = Db::name('qt_order_queue')
                        ->alias('oq')
                        ->leftJoin('qt_room r','r.id = oq.room_id')
                        ->where('oq.user_id', $item['id'])
                        ->value('r.name');
                    $workType = Db::name('qt_work_type')->where('id', $item['top_type_id'])->value('title');
                    $item['project_cate'] = $workType;
                    $item['room'] = $room_name ?? '';
                    $item['post_name'] = '';
                    if (!empty($item['post_id'])) {
                        $item['post_name'] = Db::name('qt_post')->where('id', $item['post_id'])->value('title');
                    }

                    if (!empty($item['work_time'])) {
                        $month_num = CommonService::getMonthNum(date("Y-m-d", $item['work_time']), date("Y-m-d", time()));
                        $item['work_year'] = number_format($month_num / 12, 1);
                    }
                    return $item;
                });
            $this->result('查询成功', $engineer, 200);
        }
    }

    /**
     * 更新工作状态
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function updateJobType()
    {

        if ($this->request->isPost()) {

            $post = $this->request->post();
            $engineer_id = $post['id'];
            $type = $post['type'];
            if (!in_array($type, [CommonConstant::USER_STATUS_JOB, CommonConstant::USER_STATUS_QUIT])) {
                $this->result('参数状态错误', '', 204);
            }

            if ($type == CommonConstant::USER_STATUS_QUIT) {
                //并无上班,无预约，无服务中
                $check_engineer = EngineerService::checkEngineerStatus($engineer_id);
                if ($check_engineer['code'] == FormatHelper::ERROR) {
                    $this->result($check_engineer['msg'], '', 204);
                }
            }

            switch ($type) {
                case CommonConstant::USER_STATUS_QUIT:
                    $status = CommonConstant::USER_STATUS_JOB;
                    break;

                case CommonConstant::USER_STATUS_JOB:
                    $status = CommonConstant::USER_STATUS_QUIT;
                    break;
            }

            $userInfo = $this->userInfo;
            $engineer_data = EngineerService::getEnineerById($engineer_id, $userInfo['store_id']);
            if (!empty($engineer_data)) {
                $data['id'] = $engineer_id;
                $data['status'] = $type;
                $data['update_time'] = time();
                $integralId = Db::name('qt_users')->where(['id'=>$post['id']])->update($data);
                //如果技师离职在技师排班表中删除数据
                if($type == CommonConstant::USER_STATUS_QUIT){
                    Db::name('qt_order_queue')->where('user_id',$engineer_id)->delete();
                }
                if ($type == CommonConstant::USER_STATUS_JOB) {
                    //写技师房列表
                    $max_sort = Db::name('qt_order_queue')->where(['store_id'=>$this->userInfo['store_id']])->lock(true)->max('sort');
                    Db::name('qt_order_queue')->insert([
                        'store_id'=>$this->userInfo['store_id'],
                        'user_id'=>$engineer_id,
                        'created_time'=>time(),
                        'sort'=>$max_sort+1,
                    ]);
                }
                if ($integralId) {
                    $this->result('操作成功', '', 200);
                } else {
                    $this->result('操作失败', '', 204);
                }
            } else {
                $this->result('没有查询到对应ID的数据', '', 204);
            }
        } else {
            $this->result('无效的请求', '', 204);
        }
    }

    /**
     * 添加技师
     */
    public function addEngineer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('add_engineer')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            //判断技师号好是否存在
            $find = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'group'=>'1','work_number'=>$getData['work_number']])->find();
            if(!empty($find)){
                $this->result('工号已经存在请修改工号', '', 204);
            }

            $find = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'group'=>'1','phone'=>$getData['phone']])->find();
            if(!empty($find)){
                $this->result('手机号已经存在', '', 204);
            }
            if(isset($getData['work_time']) && !empty($getData['work_time'])){
                $workTime = strtotime($getData['work_time']);
            }else{
                $workTime = null;
            }
            try {
                Db::startTrans();
                //处理数据
                $insertData['store_id'] = $this->userInfo['store_id'];
                $insertData['phone'] = $getData['phone'];
                $insertData['work_number'] = $getData['work_number'];
                $insertData['real_name'] = $getData['real_name'];
                $insertData['sex'] = $getData['sex']??0;
                $insertData['age'] = $getData['age']??0;
                $insertData['type_id'] = $getData['type_id'];
                $insertData['top_type_id'] = Db::name('qt_work_type')->where('id', $getData['type_id'])->value('pid');
                $insertData['work_time'] = $workTime;
                $insertData['overtime'] = $getData['overtime'] ?? 0;
                $insertData['role'] = '3';
                $insertData['group'] = $getData['group_id'];
                $insertData['create_time'] = time();
                $insertData['content'] = $getData['content'] ?? '';
                $insertData['add_clock_project'] = $getData['add_clock_project'] ?? 0;
                $insertData['show_wechat'] = $getData['show_wechat'] ?? 0;
                $insertData['update_project_role'] = $getData['update_project_role'] ?? 0;
                $insertData['hand_code'] = $getData['hand_code'] ?? 0;

                //插入用户数据，并返回用户ID
                $userId = Db::name('qt_users')->insertGetId($insertData);
                //插入用户门店信息
                $userStoreData = [
                    'user_id'=>$userId,
                    'store_id'=>$this->userInfo['store_id'],
                    'status'=>'0',
                ];
                Db::name('qt_user_store')->insert($userStoreData);
                //插入权限
                $auth['engineer_id'] = $userId;
                $auth['is_open'] = $getData['is_open']??0;
                $auth['is_recharge'] = $getData['is_recharge']??0;
                $auth['is_pay'] = $getData['is_pay']??0;
                $auth['is_retreat'] = $getData['is_retreat']??0;
                $auth['is_room'] = $getData['is_room']??0;
                $auth['is_hand_card'] = $getData['is_hand_card']??0;
                $auth['is_room_content'] = $getData['is_room_content']??0;
                Db::name('qt_users_auth')->insert($auth);

                //插入技师服务项目
                $projectIDs = explode(',', $getData['project_ids']);
                foreach ($projectIDs as $key => $value) {
                    $insert[$key]['engineer_id'] = $userId;
                    $insert[$key]['project_id'] = $value;
                    $insert[$key]['create_time'] = time();
                }
                Db::name('qt_user_project')->insertAll($insert);

                //更新用户信息
                $up['ivt_code'] = $userId;
                $up['login_token'] = token_rand();
                $up['password'] = pwd('123456',$userId);
                Users::where(['id' => $userId])->update($up);

                //根据手牌编号更新手牌表员工ID
                if (!empty($getData['hand_code'])) {
                    EngineerService::updateHandCard($getData['hand_code'],$userId);
                }

                //写技师房列表
                $max_sort = Db::name('qt_order_queue')->where(['store_id'=>$this->userInfo['store_id']])->lock(true)->max('sort');
                Db::name('qt_order_queue')->insert([
                    'store_id'=>$this->userInfo['store_id'],
                    'user_id'=>$userId,
                    'created_time'=>time(),
                    'sort'=>$max_sort+1,
                ]);

                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('添加失败'.$exception->getMessage(), '', 204);
            }
            $this->result('添加成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 编辑技师技师
     */
    public function editEngineer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('edit_engineer')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            try {
                Db::startTrans();
                //处理数据
                $insertData['id'] = $getData['id'];
                $insertData['phone'] = $getData['phone'];
                $insertData['work_number'] = $getData['work_number'];
                $insertData['real_name'] = $getData['real_name'];
                $insertData['sex'] = $getData['sex']??0;
                $insertData['age'] = $getData['age']??0;
                $insertData['type_id'] = $getData['type_id'];
                $insertData['top_type_id'] = $getData['type_id'];
                $insertData['work_time'] = strtotime($getData['work_time']);
                $insertData['overtime'] = $getData['overtime'];
                $insertData['role'] = '3';
                $insertData['update_time'] = time();
                $insertData['add_clock_project'] = $getData['add_clock_project'] ?? 0;
                $insertData['show_wechat'] = $getData['show_wechat']??0;
                $insertData['update_project_role'] = $getData['update_project_role']??0;
                $insertData['group'] = $getData['group'];
                $insertData['content'] = $getData['content'] ?? '';
                $insertData['hand_card_neima'] = $getData['hand_code'] ?? '';
                //更新用户数据，并返回用户ID
                Db::name('qt_users')->where('id',$getData['id'])->update($insertData);
                $userId = $getData['id'];
                //插入权限
                $auth['engineer_id'] = $userId;
                $auth['is_open'] = $getData['is_open']??0;
                $auth['is_recharge'] = $getData['is_recharge']??0;
                $auth['is_pay'] = $getData['is_pay']??0;
                $auth['is_retreat'] = $getData['is_retreat']??0;
                $auth['is_room'] = $getData['is_room']??0;
                $auth['is_hand_card'] = $getData['is_hand_card']??0;
                $auth['is_room_content'] = $getData['is_room_content']??0;
                Db::name('qt_users_auth')->where('engineer_id', $userId)->delete();//先删除
                Db::name('qt_users_auth')->insert($auth);//新增
                //插入用户房间记录
                $userStore = Db::name('qt_user_store')
                    ->where(['user_id'=>$getData['id'],'store_id'=>$this->userInfo['store_id']])
                    ->find();
                if($userStore == null){
                    $userStoreData = [
                        'user_id'=>$getData['id'],
                        'store_id'=>$this->userInfo['store_id'],
                        'status'=>'1',
                    ];
                    Db::name('qt_user_store')->insert($userStoreData);
                }

                //插入技师服务项目
                $projectIDs = explode(',', $getData['project_ids']);
                foreach ($projectIDs as $key => $value) {
                    $insert[$key]['engineer_id'] = $userId;
                    $insert[$key]['project_id'] = $value;
                    $insert[$key]['create_time'] = time();
                }

                Db::name('qt_user_project')->where('engineer_id', $userId)->delete();//先删除
                Db::name('qt_user_project')->insertAll($insert);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('修改失败'.$exception->getFile().$exception->getMessage(), '', 204);
            }
            //给技师排等位
            $projectIDs = explode(',', $getData['project_ids']);
            foreach ($projectIDs as $key => $value) {
                //安排等位
                $waitRes = Db::name('qt_wait')
                    ->where(['store_id'=>$this->userInfo['store_id'],'status'=>'1','project_id'=>$value,'delay_time'=>'0'])
                    ->order('is_first desc id desc')
                    ->find();
                if (!empty($waitRes)) {
                    $userInfo = $this->userInfo;
                    //查找可以安排的技师
                    $data['man_num'] = 0;
                    $data['woman_num'] = 0;
                    $data['other_num'] = 0;
                    if($waitRes['sex'] == '1'){
                        $data['man_num'] = $waitRes['number'];
                    }
                    if($waitRes['sex'] == '2'){
                        $data['woman_num'] = $waitRes['number'];
                    }
                    if($waitRes['sex'] == '3'){
                        $data['other_num'] = $waitRes['number'];
                    }
                    $data['project_id'] = $waitRes['project_id'];
                    $data['room_id'] = $waitRes['room_id'];
                    $data['hand_card_id'] = '';
                    $data['delay']= 0;
                    $data['time_type'] = 1;
                    $data['order_type'] = 1;
                    $data['create_id'] = $userInfo['id']?? '';
                    $orderModel = new \app\common\model\Order();
                    $code = $orderModel->create_order($data,$userInfo);
                    if($code['code'] == '200'){
                        Db::name('qt_wait')->where(['id' => $waitRes['id']])->update(['status' => '2']);
                    }
                }
            }
            $this->result('修改成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 编辑技师头像
     */
    public function editAvatar () {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['id']) || empty($post['avatar'])){
                $this->result('参数错误', '', 204);
            }
            Db::name('qt_users')->where('id',$post['id'])->update(['avatar'=>$post['avatar']]);
            $this->result('修改成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 修改手机号
     */
    public function editPhone(){

        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['id']) || empty($post['phone'])){
                $this->result('参数错误', '', 204);
            }
            Db::name('qt_users')->where('id',$post['id'])->update(['phone'=>$post['phone']]);
            $this->result('修改成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取修改的技师
     */
    public function getUser()
    {
        if ($this->request->isPost()) {

            $post = $this->request->post();
            $engineer_id = $post['id'];

            $userInfo = $this->userInfo;
            $engineer_data = EngineerService::getEnineerById($engineer_id, $userInfo['store_id']);
            unset($engineer_data['password']);
            unset($engineer_data['login_token']);
            unset($engineer_data['app_token']);
            unset($engineer_data['pc_token']);
            unset($engineer_data['shoes_token']);
            unset($engineer_data['waiter_token']);
            unset($engineer_data['engineer_room_token']);
            unset($engineer_data['engineer_token']);
            unset($engineer_data['bell_token']);
            unset($engineer_data['engineer_token']);
            if (empty($engineer_data)) {
                $this->result('没有查询到对应ID的数据', '', 204);
            }
            $users_auth = Db::name('qt_users_auth')->field('is_open,is_recharge,is_pay,is_retreat,is_room,is_hand_card,is_room_content')->where('engineer_id', $engineer_id)->find() ?? [
                    "is_open"=>0,
                    "is_recharge"=>0,
                    "is_pay"=>0,
                    "is_retreat"=>0,
                    "is_room"=>0,
                    "is_hand_card"=>0,
                    "is_room_content"=>0
                ];
            $hand_code['hand_code'] = $engineer_data['hand_card_neima'];
            $project['project_ids'] = Db::name('qt_user_project')->where('engineer_id',$engineer_id)->column('project_id')??[];
            $engineer_data = array_merge($engineer_data,$users_auth,$hand_code,$project);
            $this->result('请求成功', $engineer_data, 200);

        } else {

            $this->result('无效的请求', '', 204);
        }
    }

    /**
     * 添加楼面接口
     */
    public function addFloor(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('add_floor')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            //判断技师号好是否存在
            $find = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'group'=>'2','work_number'=>$getData['work_number']])->find();
            if(!empty($find)){
                $this->result('工号已经存在请修改工号', '', 204);
            }

            $find = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'group'=>'2','phone'=>$getData['phone']])->find();
            if(!empty($find)){
                $this->result('手机号已经存在', '', 204);
            }
            if(isset($getData['work_time']) && !empty($getData['work_time'])){
                $workTime = strtotime($getData['work_time']);
            }else{
                $workTime = null;
            }
            $insertData['work_number'] = $getData['work_number'];
            $insertData['real_name'] = $getData['real_name'];
            $insertData['sex'] = $getData['sex'];
            $insertData['post_id'] = $getData['post_id'];
            $insertData['phone'] = $getData['phone'];
            $insertData['card'] = $getData['card'];
            $insertData['work_time'] = $workTime;
            $insertData['select_report_time'] = $getData['select_report_time'];
            $insertData['select_list_time'] = $getData['select_list_time'];
            $insertData['operation'] = $getData['operation'];
            $insertData['create_time'] = time();
            $insertData['group'] = $getData['group_id'];
            $insertData['hand_card_neima'] = $getData['hand_code'];
            try{
                Db::startTrans();
                $userId = Db::name('qt_users')->insertGetId($insertData);
                //插入用户门店信息
                $userStoreData = [
                    'user_id'=>$userId,
                    'store_id'=>$this->userInfo['store_id'],
                    'status'=>'0',
                ];
                Db::name('qt_user_store')->insert($userStoreData);
                //更新用户信息
                $up['ivt_code'] = $userId;
                $up['password'] = pwd('123456',$userId);
                $up['login_token'] = token_rand();
                Db::name('qt_users')->where(['id' => $userId])->update($up);
                //插入菜单权限
                EngineerService::insertUserMenuAuth($userId,$getData['post_id']);


                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('添加失败'.$exception->getMessage(),'',204);
            }
            $this->result('添加成功','',200);
        }
    }

    /**
     * 修改楼面接口
     */
    public function editFloor(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('edit_floor')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $userInfo = $this->userInfo;
            $engineer_data = EngineerService::getEnineerById($getData['id'], $userInfo['store_id']);
            if (empty($engineer_data)) {
                $this->result('没有查询到对应ID的数据', '', 204);
            }
            $insertData['work_number'] = $getData['work_number'];
            $insertData['real_name'] = $getData['real_name'];
            $insertData['sex'] = $getData['sex'];
            $insertData['post_id'] = $getData['post_id'];
            $insertData['phone'] = $getData['phone'];
            $insertData['card'] = $getData['card'];
            $insertData['work_time'] = strtotime($getData['work_time']);
            $insertData['select_report_time'] = $getData['select_report_time'];
            $insertData['select_list_time'] = $getData['select_list_time'];
            $insertData['hand_code'] = $getData['hand_code'];
            $insertData['role_change'] = $getData['role_change'];
            $insertData['id'] = $getData['id'];
            $insertData['group'] = $getData['group_id'];
            $insertData['hand_card_neima'] = $getData['hand_code'];
            try{
                Db::startTrans();
                //更新用户信
                $insertData['login_token'] = token_rand();
                Db::name('qt_users')->where(['id'=>$getData['id']])->update($insertData);
                //插入用户房间记录
                $userStore = Db::name('qt_user_store')
                    ->where(['user_id'=>$getData['id'],'store_id'=>$this->userInfo['store_id']])
                    ->find();
                if($userStore == null){
                    $userStoreData = [
                        'user_id'=>$getData['id'],
                        'store_id'=>$this->userInfo['store_id'],
                        'status'=>'1',
                    ];
                    Db::name('qt_user_store')->insert($userStoreData);
                }
                //插入菜单权限
                EngineerService::insertUserMenuAuth($getData['id'],$getData['post_id']);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('修改失败'.$exception->getMessage(),'',204);
            }
            $this->result('修改成功','',200);
        }
    }


    /**
     * 批量更新员工状态
     */
    public function updateStatus () {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (!isset($post['status'])) {
                $this->result('参数不能为空', '', 204);
            }

            $query = Db::name('qt_users');
            if ($post['status'] == 0) {
                $query->where('status','=',1);
            }

            if ($post['status'] == 1) {
                $query->where('status','=',0);
            }

            $data['status'] = $post['status'];
            $query->where('group',2)
                ->where('status','<>',CommonConstant::USER_STATUS_QUIT)
                ->update($data);
            $this->result('修改成功','',200);
        }

        $this->result('无效的请求', '', 204);
    }

    /**
     * 更新折扣字段
     */
    public function updateDiscount () {

        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['discount']) || empty($post['id'])) {
                $this->result('参数不能为空', '', 204);
            }

            $data['discount'] = $post['discount'];
            $data['id'] = $post['id'];
            Db::name('qt_users')->update($data);
            $this->result('修改成功','',200);
        }

        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取所有技师
     */
    public function lists()
    {
        if ($this->request->isPost()) {
            $group = Db::name('qt_scheduling_type')
                ->field('id as work_type,title,start_time,end_time')
                ->where(['store_id' => $this->userInfo['store_id']])
                ->select();
            $result = [];
            foreach ($group as $key=>$value){
                $engineer = Db::name('qt_users')
                    ->field('id,work_number')
                    ->where(['store_id'=>$this->userInfo['store_id'],'work_type'=>$value['work_type'],'group'=>'1'])
                    ->where('work_type','neq','0')
                    ->select();
                foreach ($engineer as $k=>$v){
                    $engineer[$k]['type_id'] = $value['work_type'];
                    $engineer[$k]['work_title'] = $value['title'];
                    $engineer[$k]['key'] = $key;
                }
                $result[$key]['title'] = $value;
                $result[$key]['title']['data'] = $engineer;

            }
            $this->result('查询成功', $result, 200);
        }
    }

    /**
     * 技师圈牌
     */
    public function circleCard()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['engineer_id'])) {
                $this->result('缺少技师', '', 204);
            }
            $engineerIds = explode(',',$getData['engineer_id']);
            foreach ($engineerIds as $key=>$value){
                Db::name('qt_users')->where('id',$value)->update(['work_status' => '6']);
            }
            $this->result('设置成功', '', 200);
        }
    }

    /**
     * 技师圈牌
     */
    public function delCircleCard()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['engineer_id'])) {
                $this->result('缺少技师', '', 204);
            }
            $engineerIds = explode(',',$getData['engineer_id']);
            foreach ($engineerIds as $key=>$value){
                Db::name('qt_users')->where('id', $value)->update(['work_status' => '1']);
            }
            $this->result('设置成功', '', 200);
        }
    }


    /**
     * 获取所有圈牌的技师
     */
    public function get_CircleCard(){
        if ($this->request->isPost()) {
            $data= Db::name('qt_users')
                ->field('id,work_number')
                ->where(['store_id'=>$this->userInfo['store_id'],'work_status'=>'6','role'=>'3'])
                ->select();
            $this->result('查询成功', $data, 200);

        }
    }


    /**
     * 获取未排班技师列表
     * @throws Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function noScheduling()
    {
        if ($this->request->isPost()) {
            $data = Db::name('qt_users')
                ->field('id,real_name,work_number')
                ->where(['store_id'=>$this->userInfo['store_id'],'status'=>'0','work_type'=>'0','group'=>'1'])
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 技师排班
     * @throws Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function scheduling()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['engineer_ids'])){
                $this->result('缺少参数', '', 204);
            }
            $engineerIds = explode(',',$getData['engineer_ids']);
            foreach ($engineerIds as $key=>$value){
                Db::name('qt_users')->where('id',$value)->update(['work_type'=>$getData['type_id']]);
            }
            $this->result('排班成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 删除技师班次
     * @throws Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function del_scheduling()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $userIds = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'work_type'=>$getData['id']])->column('id');
            try{
                //删除班次
                Db::name('qt_scheduling_type')->where('id',$getData['id'])->delete();
                //更新技师班次
                foreach ($userIds as $key=>$value){
                    Db::name('qt_users')->where('id',$value)->update(['work_type'=>0]);
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                $this->result('删除失败', '', 204);
            }
            $this->result('删除成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 排序
     */
    public function sort(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $userInfo = $this->userInfo;
            $list =  Db::name('qt_users')->where(['store_id'=>$userInfo['store_id'],'role'=>'3'])->order('sort asc')->select();
            $oldSort  = $getData['old_sort'];
            $newSort = $getData['new_sort'];
            //id 主键 sort 排序值
            //id集合
            $idArr   = [];
            //排序集合
            $sortArr = [];
            foreach ($list as $item) {
                $idArr[]   = $item['id'];
                $sortArr[] = $item['sort'];
            }
            //记录要拖动的id
            $oldValue = $idArr[$oldSort];
            //删除这个要拖动的id
            unset($idArr[$oldSort]);
            //插入新的位置，并自动移位
            array_splice($idArr, $newSort, 0, $oldValue);
            //重新设置排序
            $set = [];
            for ($i = 0; $i < count($idArr); $i++) {
                $set[$i]['id']   = $idArr[$i];
                $set[$i]['sort'] = $sortArr[$i];
            }
            //保存到数据库
            $prepareQueue = new Users();
            if($prepareQueue->saveAll($set)){
                $this->result('排序成功', '', 200);
            }
            $this->result('排序失败', '', 204);
        }

    }


    /**
     * 一键上班
     */
    public function all_go_work(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['type']) || empty($getData['work_type'])){
                $this->result('缺少参数', '', 204);
            }
            if($getData['type'] == '1'){
                //上班
                $workStatus = '1';
                $isAdd = '1';
            }elseif ($getData['type'] == '2'){
                //下班
                $workStatus = '2';
                $isAdd = '2';
            }
            $userRes = Db::name('qt_users')
                ->where(['store_id'=>$this->userInfo['store_id'],'role'=>'3','work_type'=>$getData['work_type']])
                ->where('work_status','<','3')
                ->column('id');
            foreach ($userRes as $key=>$value){
                Db::name('qt_users')->where('id',$value)->update(['work_status'=>$workStatus,'is_add'=>$isAdd]);
            }
            $this->result('一键上下班成功', '', 200);
        }
    }


    /**
     * 根据技师获取详细信息
     */
    public function getRoomInfo(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['engineer_id'])){
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_order_queue')
                ->field('oq.*,p.name as project_name')
                ->alias('oq')
                ->leftJoin('qt_project p','p.id = oq.project_id')
                ->where(['user_id'=>$getData['engineer_id']])
                ->find();
            if($data['project_id'] != null){
                $man = Db::name('qt_user_project')
                    ->alias('p')
                    ->leftJoin('qt_users u', 'u.id = p.engineer_id')
                    ->where('p.project_id', $data['project_id'])
                    ->where(['u.sex' => '1', 'work_status' => '1'])
                    ->count();
                $girl = Db::name('qt_user_project')
                    ->alias('p')
                    ->leftJoin('qt_users u', 'u.id = p.engineer_id')
                    ->where('p.project_id', $data['project_id'])
                    ->where(['u.sex' => '2', 'work_status' => '1'])
                    ->count();
                $data['man'] = $man;
                $data['woman'] = $girl;
                $data['room_name'] = Db::name('qt_room')->where('id',$data['room_id'])->value('name');
            }else{
                $data['man'] = 0;
                $data['woman'] = 0;
                $data['room_name'] = '';
            }

            $this->result('查询成功', $data, 200);
        }
    }




}
